﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using TRL.DataAccessLayer;
using System.Linq;
using System.Net.Mail;

namespace TRL.OnlineSignUp
{
    public class FinishSignUp : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var r = context.Request;
            var token = r.Params["token"];
            var payerId = r.Params["payerId"];

            if (String.IsNullOrEmpty(token) || String.IsNullOrEmpty(payerId))
            {
                context.Response.Write("Paypal token or payerId was not specified.");
                return;
            }

            InterimMembership intermMembershipRow;
            var dc = new DataClasses1DataContext();
            try
            {
                intermMembershipRow =   (from IntermMembership in dc.InterimMemberships
                                        where IntermMembership.paypalToken == token
                                        select IntermMembership).First();
            }
            catch
            {
                context.Response.Write("Could not associate membership with paypal token.");
                return;            
            }

            var paypal = new NVPAPICaller();

            string retMsg = "";
            NVPCodec decoder = new NVPCodec();
            bool ret = paypal.ConfirmPayment(intermMembershipRow.amountPaid.ToString(), token, payerId, ref decoder, ref retMsg);
            if (ret)
            {
                // Unique transaction ID of the payment. Note:  If the PaymentAction of the request was Authorization or Order, this value is your AuthorizationID for use with the Authorization & Capture APIs. 
                string transactionId = decoder["PAYMENTINFO_0_TRANSACTIONID"];
                intermMembershipRow.paymentAuthCode = transactionId;

                // Time/date stamp of payment
                string orderTime = decoder["PAYMENTINFO_0_ORDERTIME"];
                intermMembershipRow.paymentDate = DateTime.Parse(orderTime);

                dc.SubmitChanges();
            }
            else
            {
                context.Response.Redirect("APIError.aspx?" + retMsg);
                return;
            }

            // Send email indicating signup
            MailMessage msg = new MailMessage();
            msg.To.Add(new MailAddress("membership@redlizardrunning.com"));
            msg.CC.Add(new MailAddress("jeffwhuber@outlook.com"));
            msg.From = new MailAddress("membership@redlizardrunning.com");
            msg.Subject = "A Team Red Lizard Member has Signed Up or Renewed";

            String newOrRenewal;
            if (intermMembershipRow.newOrRenewal == 'n')
                newOrRenewal = "new membership";
            else
                newOrRenewal = "renewal";

            msg.Body = String.Format("Payment for a Team Red Lizard {1} has been received on {0}. The following are the details:\n", ((DateTime)intermMembershipRow.paymentDate).ToString("f"), newOrRenewal);
            
            var fieldsForEmail =new Dictionary<string,string>();
            fieldsForEmail.Add("Membership Type", "membershipType");
            fieldsForEmail.Add("First name", "firstName");
            fieldsForEmail.Add("Last name", "lastName");
            fieldsForEmail.Add("Address", "address");
            fieldsForEmail.Add("City", "city");
            fieldsForEmail.Add("State", "state");
            fieldsForEmail.Add("Zipcode", "postalCode");
            fieldsForEmail.Add("Phone", "phoneNumber");
            fieldsForEmail.Add("Email", "email");
            fieldsForEmail.Add("Forum username", "forumUsername");
            fieldsForEmail.Add("Date of birth", "dob");
            fieldsForEmail.Add("Gender", "gender");
            fieldsForEmail.Add("Shirt size", "shirtSize");
            fieldsForEmail.Add("Occupation", "occupation");

            var familyFieldsForEmail =new Dictionary<string,string>();
            familyFieldsForEmail.Add("First name", "secondFirstName");
            familyFieldsForEmail.Add("Last name", "secondLastName");
            familyFieldsForEmail.Add("Email", "secondEmail");
            familyFieldsForEmail.Add("Forum username", "secondForumUsername");
            familyFieldsForEmail.Add("Date of birth", "secondDob");
            familyFieldsForEmail.Add("Gender", "secondGender");
            familyFieldsForEmail.Add("Shirt size", "secondShirtSize");
            familyFieldsForEmail.Add("Occupation", "secondOccupation");

            foreach (var fields in fieldsForEmail)
            {
                string fieldValue;
                if (fields.Value == "membershipType")
                {
                    if (intermMembershipRow.membershipType == 2)
                        fieldValue = "Family";
                    else
                        fieldValue = "Individiual";
                }
                else if (fields.Value == "dob")
                {
                    if (intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow) != null)
                        fieldValue = ((DateTime)intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow)).ToShortDateString();
                    else
                        fieldValue = "";
                }
                else
                {
                    fieldValue = intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow) as string;
                }

                msg.Body += String.Format("{0}: {1}\n", fields.Key, fieldValue);
            }

            // If family membership, display family fields
            if (intermMembershipRow.membershipType == 2)
            {
                msg.Body += "\n\nBelow are details of the second person in the family membership:\n";
                foreach (var fields in familyFieldsForEmail)
                {
                    string fieldValue;
                    if (fields.Value == "secondDob")
                    {
                        if (intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow) != null)
                            fieldValue = ((DateTime)intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow)).ToShortDateString();
                        else
                            fieldValue = "";
                    }
                    else
                    {
                        fieldValue = intermMembershipRow.GetType().GetProperty(fields.Value).GetValue(intermMembershipRow) as string;
                    }
                   
                    msg.Body += String.Format("{0}: {1}\n", fields.Key, fieldValue);
                }
            }

            msg.Body += String.Format("\n\nTotal amount paid: {0}\n", intermMembershipRow.amountPaid);
            msg.Body += String.Format("Occured from IP address: {0}\n", intermMembershipRow.IPAddressFrom);
            msg.Body += String.Format("Initiated on: {0}\n", intermMembershipRow.addedOn);
            msg.Body += String.Format("Payment received on: {0}\n", intermMembershipRow.paymentDate);
            msg.Body += String.Format("Authorization code: {0}\n", intermMembershipRow.paymentAuthCode);

            SmtpClient client = new SmtpClient();
            client.Send(msg);

            context.Response.Redirect("http://redlizardrunning.com/membership-thank-you/");
        }



    }
}

